package com.jbp.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jbp.utils.HttpClient;
import io.agora.media.RtcTokenBuilder2;
import io.agora.rtm.RtmTokenBuilder;
import io.agora.rtm.RtmTokenBuilder2;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 声网
 * @author cc
 * @since 2020-10-14 10:42:04
 */
@Service
public class AgoraService {
    @Autowired
    private AppConfigService appConfigService;
    // 客户 ID
    final String customerKey = "2f899985c0d84f4b9bb43fbff45a5054";
    // 客户密钥
    final String customerSecret = "cec3523596824443b5d851ea83665595";

    /*public String getRtctoken(String channelName, int uid, boolean upMai){
        String appId = appConfigService.getV("agora_appid");
        String appCertificate = appConfigService.getV("agora_cert");
        int expirationTimeInSeconds = 60*60*24;

        RtcTokenBuilder token = new RtcTokenBuilder();
        int timestamp = (int)(System.currentTimeMillis() / 1000 + expirationTimeInSeconds);

        String result = token.buildTokenWithUid(appId, appCertificate,
                channelName, uid, upMai ? RtcTokenBuilder.Role.Role_Publisher : RtcTokenBuilder.Role.Role_Subscriber, timestamp);
        return result;
    }*/


    public String getRtctoken(String channelName, int uid, boolean upMai){
        String appId = appConfigService.getV("agora_appid");
        String appCertificate = appConfigService.getV("agora_cert");
        int expirationTimeInSeconds = 60*60*24;
//        int expirationTimeInSeconds = 60*2;

        // 所有的权限的有效时间，单位秒，声网建议你将该参数和 Token 的有效时间设为一致
        int privilegeExpirationInSeconds = 60*60*24;
//        int privilegeExpirationInSeconds = 60*2;

        RtcTokenBuilder2 token = new RtcTokenBuilder2();
        int timestamp = (int)(System.currentTimeMillis() / 1000 + expirationTimeInSeconds);

        //旧版本文档写法
        /*String result = token.buildTokenWithUid(appId, appCertificate,
                channelName, uid, upMai ? RtcTokenBuilder.Role.Role_Publisher : RtcTokenBuilder.Role.Role_Subscriber, timestamp);*/
        //新文档写法
        /*String result = token.buildTokenWithUid(appId, appCertificate,
                channelName, uid, Role.ROLE_PUBLISHER, tokenExpirationInSeconds, privilegeExpirationInSeconds);*/

        /*String result = token.buildTokenWithUid(appId, appCertificate,
                channelName, uid, upMai ? RtcTokenBuilder2.Role.Role_Publisher : RtcTokenBuilder.Role.Role_Subscriber, expirationTimeInSeconds, privilegeExpirationInSeconds);
*/
        String result = token.buildTokenWithUid(appId, appCertificate, channelName, uid, RtcTokenBuilder2.Role.ROLE_PUBLISHER, expirationTimeInSeconds, privilegeExpirationInSeconds);
        return result;
    }



    /*public String getRtmtoken(@RequestParam("uid") String uid){
        String appId = appConfigService.getV("agora_appid");
        String appCertificate = appConfigService.getV("agora_cert");
        int expirationTimeInSeconds = 60*60*24;

        RtmTokenBuilder token = new RtmTokenBuilder();
        String result = null;
        try {
            result = token.buildToken(appId, appCertificate, uid, RtmTokenBuilder.Role.Rtm_User, expirationTimeInSeconds);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }*/


    public String getRtmtoken(@RequestParam("uid") String uid){
        String appId = appConfigService.getV("agora_appid");
        String appCertificate = appConfigService.getV("agora_cert");
        int expirationTimeInSeconds = 60*60*24;
//        int expirationTimeInSeconds = 60*2;

        RtmTokenBuilder2 token = new RtmTokenBuilder2();
        String result = null;
        try {
            result = token.buildToken(appId, appCertificate, uid, expirationTimeInSeconds);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 踢掉
     * */
    public void addRule(Integer uid){
        // 填入客户 ID（customerId）和客户密钥（customerSecret），计算 plainCredentials。
        String plainCredentials = customerKey + ":" + customerSecret;
        // 填入 plainCredentials，计算 base64Credentials（使用 Base64 算法编码）。
        String base64Credentials = new String(Base64.encodeBase64(plainCredentials.getBytes()));

        Map<String, Object> head = new HashMap<>();
        head.put("Authorization", "Basic " + base64Credentials);

        String appId = appConfigService.getV("agora_appid");
//        String appId = "57f590de07db4cc98464b4ffb2266c29";
        Map<String, Object> params = new HashMap<>();
        String url = "https://api.agora.io/dev/v1/kicking-rule";
        params.put("appid", appId);
        params.put("uid", uid);
        params.put("time", 1);
        params.put("privileges", new String[]{"join_channel"});

        HttpClient.doPostJson(params, head, url);
    }

    public static void main(String[] args) {
//        addRule(12);
//        getRules();
    }

    public void getRules(){
        // 填入客户 ID（customerId）和客户密钥（customerSecret），计算 plainCredentials。
        String plainCredentials = customerKey + ":" + customerSecret;
        // 填入 plainCredentials，计算 base64Credentials（使用 Base64 算法编码）。
        String base64Credentials = new String(Base64.encodeBase64(plainCredentials.getBytes()));

        Map<String, Object> head = new HashMap<>();
        head.put("Authorization", "Basic " + base64Credentials);

        String appId = appConfigService.getV("agora_appid");
//        String appId = "57f590de07db4cc98464b4ffb2266c29";

        try {
            String result = HttpClient.doGet(head, "https://api.agora.io/dev/v1/kicking-rule?appid=" + appId);
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**获取用户列表*/
    public List<Integer> getUsers(Integer roomId){
        // 填入客户 ID（customerId）和客户密钥（customerSecret），计算 plainCredentials。

        // 拼接客户 ID 和客户密钥并使用 base64 编码
        String plainCredentials = customerKey + ":" + customerSecret;
//        String plainCredentials = "69d1e003af21448cb9c02c4b6de8df1c:d8923b05a59743c8bd0ca56ceef5280d";
        // 填入 plainCredentials，计算 base64Credentials（使用 Base64 算法编码）。
        String base64Credentials = new String(Base64.encodeBase64(plainCredentials.getBytes()));

        Map<String, Object> head = new HashMap<>();
        head.put("Authorization", "Basic " + base64Credentials);

        String appId = appConfigService.getV("agora_appid");
//        String appId = "57f590de07db4cc98464b4ffb2266c29";

        try {
            String result = HttpClient.doGet(head, "https://api.agora.io/dev/v1/channel/user/" + appId+"/"+roomId);
            JSONObject jsonObject = JSON.parseObject(result);
            JSONObject data = jsonObject.getJSONObject("data");
            if (data !=null) {
                JSONArray users = data.getJSONArray("users");
                if (users != null) {
                    List<Integer> ids = users.toJavaList(Integer.class);
//                    System.out.println(ids.toString());
                    return ids;
                }
            }
//            System.out.println(result);
        } catch (Exception e) {
//            e.printStackTrace();
        }

        return null;
    }
}
